/**
 *      example of use :
 *              app.websocket({
 *                      onopen: function(){...},
 *                      onmessage: function(message){...},
 *                      onclose: function(){...},
 *                      onerror: function(){...}
 *              });
 */
(function (app) {
  var namespace = namespace || 'app';
  if(typeof (window[namespace]) === 'undefined') {
    return;
  }
  var url;
  var close;
  var open;
  var message;
  var error;
  var WEB_SOCKET = window.hasOwnProperty('WebSocket');
  var MOZ_WEB_SOCKET = window.hasOwnProperty('MozWebSocket');
  var NO_WEB_SOCKET = !window.hasOwnProperty('WebSocket') && !window.hasOwnProperty('MozWebSocket');
  var init = function (_) {
      url = _.url || 'ws://';
      close = _.onclose ||
      function () {};
      open = _.onopen ||
      function () {};
      message = _.onmessage ||
      function () {};
      error = _.onerror ||
      function () {};
    }
  var proceed = function (options) {
      var transport = null,
        ar = ['url', 'onclose', 'onopen', 'onmessage', 'onerror'];
      options = options || {};
      for(var i = 0; i < ar.length; i++) {
        if(!options.hasOwnProperty(ar[i])) {
          options[ar[i]] = '';
        }
      }
      init(options);
      if(NO_WEB_SOCKET) return;
      else if(WEB_SOCKET) transport = new WebSocket(_url);
      else if(MOZ_WEB_SOCKET) transport = new MozWebSocket(_url);
      transport.onopen = open;
      transport.onmessage = message;
      transport.onclose = close;
      transport.onerror = error;
    }
  window[namespace].websocket = proceed;
}());
